import { useEffect, useRef } from 'react'
import THREEProject from '../utils/index'
import {arrNomarlize} from '../utils/helper'
/**
 * 三个点一个三角形
 * 六个点一个四边形(其中两个点是重复的) 
 * 
 */


const VertexColor = () => {
  const can = useRef(null)
  const pro = new THREEProject([10, 0, 10])
  const { thr, renderer, scene, axes, camera, controls } = pro
  const fileLoader = new thr.FileLoader()
  const init = () => {
    scene.add(axes)

    const geometry = new thr.BufferGeometry()
    console.log("🚀 ~ file: VertexColor.js ~ line 14 ~ init ~ geometry", geometry)


    const rectShapeX = function(x, y, z, w=10) {
      return [
        [x, y, z],
        [x+w, y, z],
        [x, y+w, z],

        [x+w, y, z],
        [x, y+w, z],
        [x+w, y+w, z],
      ]
    }
    const rectShapeZ = function(x, y, z, w=10) {
      return [
        [x, y, z],
        [x, y, z+w],
        [x, y+w, z],

        [x, y, z+w],
        [x, y+w, z],
        [x, y+w, z+w],
      ]
    }
    const rectShapeY = function(x, y, z, w=10) {
      return [
        [x, y, z],
        [x+w, y, z],
        [x, y, z+w],

        [x+w, y, z],
        [x, y, z+w],
        [x+w, y, z+w],
      ]
    }

    const vertices = [
      ...rectShapeX(0,0,0),
      ...rectShapeX(10,0,0),
      ...rectShapeX(0,0,10),
      ...rectShapeY(0,0,0),
      ...rectShapeY(10,0,0),
      ...rectShapeZ(0,0,0),
      ...rectShapeX(10,0,10),
      ...rectShapeZ(20,0,0)
    ]
    const colors = vertices.map(point => {
      if(!point[0] && !point[1] && !point[2]) {
        return [1,1,1]
      }
      if(!point[0] && !point[1]) {
        return [1,1,0]
      }
      if(point[1] > 0) {
        return [0,1,1]
      }
      return [0,0,1]
    })
    geometry.setAttribute('position', new thr.BufferAttribute( new Float32Array(vertices.flat()), 3))
    geometry.setAttribute('color', new thr.BufferAttribute( new Float32Array(colors.flat()), 3))
    const material = new thr.MeshBasicMaterial({
      side: thr.DoubleSide,
      vertexColors: true,
    })
    scene.add(new thr.Mesh(geometry, material))
    scene.add(new thr.AmbientLight(0xffffff))
    appendRenderDom()
    animate()
  }


  const appendRenderDom = () => {
    if(!can.current.children.length) {
      can.current.appendChild(renderer.domElement)
    }
  }

  const render = () => {
    controls.update()
    renderer.render(scene, camera)
  }

  const animate = () => {
    requestAnimationFrame(animate)
    render()
  }

  useEffect(init, [])

  return (
    <div ref={can}></div>
  )
}

export default VertexColor
export {
  VertexColor
}